import React, { useState, useEffect } from 'react';
import { Modal, Form, InputNumber, Button, Upload, ConfigProvider, message, theme, Switch } from 'antd';
import { UploadOutlined } from '@ant-design/icons';
import { updateSegments, uploadVideoFile, createSegment } from '@/services/project';
import eventBus from '@/utils/eventBus';
import axios from 'axios';
import { getMediaDuration, secondsToMicroseconds } from '@/utils/mediaUtils';
import { getTrackLastSegmentEndTime } from '@/utils/trackUtils';
import { useSelector } from 'react-redux';
import { RootState } from '@/store';
import { selectTracks } from '@/store/draftsSlice';

interface AddAudioClipModalProps {
    visible: boolean;
    trackId: string;
    draftId: string;
    renderIndex: number;
    onCancel: () => void;
}

// 音频转文字接口返回的数据结构
interface AudioTranscriptionResult {
    end_time: string;
    line: number;
    start_time: string;
    text: string;
}

// 默认文字片段配置
const DEFAULT_SEGMENT_CONFIG = {
    styles: [
        {
            fill: {
                alpha: 1.0,
                content: {
                    render_type: 'solid',
                    solid: {
                        alpha: 1.0,
                        color: [1.0, 0.0, 0.0],
                    },
                },
            },
            range: [0, 11],
            size: 12.0,
            bold: true,
            italic: false,
            underline: false,
            strokes: [
                {
                    width: 1.0,
                    content: {
                        solid: {
                            alpha: 1.0,
                            color: [1.0, 0.0, 0.0],
                        },
                    },
                },
            ],
        },
    ],
    clip: {
        alpha: 1.0,
        flip: {
            horizontal: false,
            vertical: false,
        },
        rotation: 0.0,
        scale: {
            x: 1.0,
            y: 1.0,
        },
        transform: {
            x: 0.0,
            y: 0.0,
        },
    },
};

// 暗黑主题配置
const darkTheme = {
    algorithm: theme.darkAlgorithm,
    token: {
        colorBgElevated: '#1f1f1f',
        colorBgContainer: '#1f1f1f',
        colorBorder: '#434343',
        colorText: '#ffffff',
        colorTextSecondary: 'rgba(255, 255, 255, 0.65)',
        colorPrimary: '#1890ff',
        colorSuccess: '#52c41a',
        colorWarning: '#faad14',
        colorError: '#ff4d4f',
        borderRadius: 8,
        boxShadow: '0 4px 12px rgba(0, 0, 0, 0.5)',
    },
    components: {
        Modal: {
            contentBg: '#1f1f1f',
            headerBg: '#1f1f1f',
            titleColor: '#ffffff',
            colorText: '#ffffff',
        },
        Form: {
            labelColor: '#ffffff',
            colorText: '#ffffff',
        },
        InputNumber: {
            colorBgContainer: '#2a2a2a',
            colorBorder: '#434343',
            colorText: '#ffffff',
            colorTextPlaceholder: 'rgba(255, 255, 255, 0.45)',
        },
        Button: {
            colorBgContainer: '#2a2a2a',
            colorBorder: '#434343',
            colorText: '#ffffff',
            colorPrimary: '#1890ff',
            colorPrimaryHover: '#40a9ff',
        },
        Upload: {
            colorBgContainer: '#2a2a2a',
            colorBorder: '#434343',
            colorText: '#ffffff',
        },
        Slider: {
            colorPrimary: '#1890ff',
            colorPrimaryBorder: '#1890ff',
            colorPrimaryHover: '#40a9ff',
            trackBg: '#1890ff',
            trackHoverBg: '#40a9ff',
            handleColor: '#1890ff',
            handleActiveColor: '#40a9ff',
            railBg: '#434343',
            railHoverBg: '#595959',
        },
    },
};

const AddAudioClipModal: React.FC<AddAudioClipModalProps> = ({ visible, trackId, draftId, renderIndex, onCancel }) => {
    const [form] = Form.useForm();
    const [uploading, setUploading] = useState(false);
    const [audioFile, setAudioFile] = useState<File | null>(null);
    const [mediaDuration, setMediaDuration] = useState<number>(0);
    const [autoStartTime, setAutoStartTime] = useState<number>(0);
    const [enableTranscription, setEnableTranscription] = useState<boolean>(false);

    // 获取当前轨道信息
    const draft = useSelector((state: RootState) => state.drafts);
    const allTracks = selectTracks({ draft: draft }) || [];
    const currentTrack = allTracks.find((track: any) => track.id === trackId);

    // 计算自动开始时间
    useEffect(() => {
        if (currentTrack) {
            const lastEndTime = getTrackLastSegmentEndTime(currentTrack);
            setAutoStartTime(lastEndTime);
        } else {
            setAutoStartTime(0);
        }
    }, [currentTrack]);

    // 当文件选择时，获取媒体时长
    const handleFileSelect = async (file: File) => {
        setAudioFile(file);
        try {
            const duration = await getMediaDuration(file);
            setMediaDuration(duration);

            // 自动设置表单值
            form.setFieldsValue({
                start: autoStartTime,
                duration: secondsToMicroseconds(duration),
            });
        } catch (error) {
            console.error('获取媒体时长失败:', error);
            message.error('无法获取媒体文件时长');
        }
    };

    const handleUploadAndSubmit = async () => {
        try {
            // 验证表单
            const values = await form.validateFields();

            // 检查是否选择了音频文件
            if (!audioFile) {
                message.error('请先选择音频文件');
                return;
            }

            setUploading(true);

            // 第一步：上传音频文件（使用通用的文件上传接口）
            const uploadFormData = new FormData();
            uploadFormData.append('file', audioFile);

            uploadVideoFile(uploadFormData)
                .then((uploadResponse) => {
                    return uploadResponse.data;
                })
                .then(async (uploadData) => {
                    // 如果用户启用了转文字功能，使用批量创建接口
                    if (enableTranscription) {
                        // 准备片段数据数组
                        const segmentsData = [];

                        // 添加音频片段
                        segmentsData.push({
                            type: 'audio',
                            file_id: uploadData.id,
                            start: values.start,
                            duration: values.duration,
                            render_index: renderIndex,
                            segment_config: {
                                volume: values.segment_config.volume,
                            },
                        });

                        // 尝试转文字
                        try {
                            const audioTranscriptionFormData = new FormData();
                            audioTranscriptionFormData.append('file', audioFile!);
                            audioTranscriptionFormData.append('model', 'tiny');
                            audioTranscriptionFormData.append('language', 'auto');
                            audioTranscriptionFormData.append('response_format', 'json');

                            const transcriptionResponse = await axios.post('audio-transcribe/v1/audio/transcriptions', audioTranscriptionFormData, {
                                headers: {
                                    'Content-Type': 'multipart/form-data',
                                },
                            });

                            const transcriptions = transcriptionResponse.data as AudioTranscriptionResult[];

                            // 遍历transcriptions数组，为每个文字创建文本片段
                            if (transcriptions && transcriptions.length > 0) {
                                // 为每个文字片段设置固定持续时间（微秒）
                                const textDuration = 3000000; // 3秒

                                transcriptions.forEach((transcription, index) => {
                                    // 计算文本片段的开始时间，根据顺序累加
                                    const textStartTime = index * textDuration;

                                    // 创建文本片段
                                    segmentsData.push({
                                        type: 'text',
                                        start: textStartTime,
                                        duration: textDuration,
                                        render_index: renderIndex,
                                        segment_config: {
                                            text: transcription.text || '',
                                            styles: DEFAULT_SEGMENT_CONFIG.styles,
                                            clip: DEFAULT_SEGMENT_CONFIG.clip,
                                        },
                                    });
                                });
                            }
                        } catch (transcriptionError) {
                            console.warn('音频转文字失败，但音频片段仍会正常添加:', transcriptionError);
                            message.warning('音频转文字失败，但音频片段已成功添加');
                        }

                        // 使用批量创建接口
                        const createSegmentData = {
                            segments: segmentsData,
                        };
                        return updateSegments(draftId, trackId, createSegmentData);
                    } else {
                        // 如果用户没有启用转文字功能，使用单个创建接口
                        const segmentData = {
                            type: 'audio',
                            file_id: uploadData.id,
                            start: values.start,
                            duration: values.duration,
                            render_index: renderIndex,
                            segment_config: {
                                volume: values.segment_config.volume,
                            },
                        };
                        return createSegment(draftId, trackId, segmentData);
                    }
                })
                .then(() => {
                    // 触发事件总线通知更新
                    eventBus.emit('track:added', {
                        trackType: 'audio',
                        trackId,
                    });
                    // 触发片段配置更新事件，通知 VideoPreview 重新渲染
                    eventBus.emit('segmentConfig:updated', {
                        draftId,
                        trackId,
                        segmentId: 'new', // 新创建的片段
                        config: {
                            volume: values.segment_config.volume,
                        }
                    });
                    message.success('片段创建成功');
                    // 重置表单并关闭模态框
                    form.resetFields();
                    setAudioFile(null);
                    onCancel();
                })
                .catch((uploadError) => {
                    console.error('上传或创建片段失败:', uploadError);
                    message.error('操作失败，请重试');
                })
                .finally(() => {
                    setUploading(false);
                });
        } catch (formError) {
            console.error('表单验证失败:', formError);
            message.error('请检查表单填写是否正确');
        }
    };

    const handleCancel = () => {
        form.resetFields();
        setAudioFile(null);
        // 调用父组件传递的onCancel函数关闭模态框
        onCancel();
    };

    const handleUpload = (file: File) => {
        handleFileSelect(file);
        return false; // 阻止自动上传
    };

    const uploadProps = {
        accept: 'audio/*',
        beforeUpload: handleUpload,
        showUploadList: false,
        multiple: false,
    };

    return (
        <Modal
            title="添加音频片段"
            open={visible}
            onCancel={uploading ? undefined : handleCancel}
            destroyOnClose
            footer={null}
            width={700}
            centered
            zIndex={9999}
            closable={!uploading}
            maskClosable={!uploading}
            styles={{
                mask: {
                    backdropFilter: 'blur(8px)',
                },
            }}
            className="dark-theme-modal"
        >
            <ConfigProvider theme={darkTheme}>
                <Form
                    form={form}
                    layout="vertical"
                    initialValues={{
                        start: 10000000,
                        duration: 20000000,
                        segment_config: {
                            volume: '1',
                        },
                    }}
                >
                    {/* 显示已选择的音频文件 */}
                    {audioFile && (
                        <div
                            style={{
                                marginBottom: 24,
                                padding: '16px',
                                backgroundColor: '#2a2a2a',
                                borderRadius: '8px',
                                border: '1px solid #434343',
                                boxShadow: '0 2px 8px rgba(0, 0, 0, 0.3)',
                            }}
                        >
                            <div
                                style={{
                                    color: '#ffffff',
                                    fontSize: '14px',
                                    fontWeight: 600,
                                    marginBottom: '8px',
                                    display: 'flex',
                                    alignItems: 'center',
                                    gap: '8px',
                                }}
                            >
                                <span style={{ color: '#1890ff' }}>🎵</span>
                                已选择音频文件
                            </div>
                            <div
                                style={{
                                    color: 'rgba(255, 255, 255, 0.85)',
                                    fontSize: '13px',
                                    marginBottom: '8px',
                                    fontFamily: 'monospace',
                                    backgroundColor: '#1a1a1a',
                                    padding: '6px 8px',
                                    borderRadius: '4px',
                                    border: '1px solid #333',
                                }}
                            >
                                {audioFile.name}
                            </div>
                            <div
                                style={{
                                    color: '#52c41a',
                                    fontSize: '12px',
                                    fontWeight: 500,
                                    display: 'flex',
                                    alignItems: 'center',
                                    gap: '4px',
                                }}
                            >
                                <span>⏱️</span>
                                文件时长: {Math.floor(mediaDuration)}秒
                            </div>
                        </div>
                    )}

                    {/* 自动配置信息 */}
                    {audioFile && (
                        <div
                            style={{
                                marginBottom: 24,
                                padding: '16px',
                                background: 'linear-gradient(135deg, #1a3a1a 0%, #2d5a2d 100%)',
                                borderRadius: '8px',
                                border: '1px solid #52c41a',
                                boxShadow: '0 2px 8px rgba(82, 196, 26, 0.2)',
                            }}
                        >
                            <div
                                style={{
                                    color: '#52c41a',
                                    fontSize: '14px',
                                    fontWeight: 600,
                                    marginBottom: '12px',
                                    display: 'flex',
                                    alignItems: 'center',
                                    gap: '8px',
                                }}
                            >
                                <span>⚙️</span>
                                自动配置信息
                            </div>
                            <div
                                style={{
                                    display: 'flex',
                                    flexDirection: 'column',
                                    gap: '8px',
                                }}
                            >
                                <div
                                    style={{
                                        color: 'rgba(255, 255, 255, 0.9)',
                                        fontSize: '13px',
                                        display: 'flex',
                                        alignItems: 'center',
                                        gap: '8px',
                                        padding: '6px 8px',
                                        backgroundColor: 'rgba(0, 0, 0, 0.2)',
                                        borderRadius: '4px',
                                    }}
                                >
                                    <span style={{ color: '#1890ff' }}>🕐</span>
                                    <span>开始时间: {Math.floor(autoStartTime / 1000000)}秒</span>
                                    <span style={{ color: '#52c41a', fontSize: '11px' }}>(自动计算)</span>
                                </div>
                                <div
                                    style={{
                                        color: 'rgba(255, 255, 255, 0.9)',
                                        fontSize: '13px',
                                        display: 'flex',
                                        alignItems: 'center',
                                        gap: '8px',
                                        padding: '6px 8px',
                                        backgroundColor: 'rgba(0, 0, 0, 0.2)',
                                        borderRadius: '4px',
                                    }}
                                >
                                    <span style={{ color: '#faad14' }}>⏱️</span>
                                    <span>持续时间: {Math.floor(mediaDuration)}秒</span>
                                    <span style={{ color: '#52c41a', fontSize: '11px' }}>(根据文件时长)</span>
                                </div>
                            </div>
                        </div>
                    )}

                    {/* 隐藏的表单字段，用于提交数据 */}
                    <Form.Item name="start" style={{ display: 'none' }}>
                        <InputNumber />
                    </Form.Item>
                    <Form.Item name="duration" style={{ display: 'none' }}>
                        <InputNumber />
                    </Form.Item>

                    {/* 音频配置 */}
                    {audioFile && (
                        <div
                            style={{
                                marginBottom: 24,
                                padding: '16px',
                                background: 'linear-gradient(135deg, #1a3a1a 0%, #2d5a2d 100%)',
                                borderRadius: '8px',
                                border: '1px solid #52c41a',
                                boxShadow: '0 2px 8px rgba(82, 196, 26, 0.2)',
                            }}
                        >
                            <div
                                style={{
                                    color: '#52c41a',
                                    fontSize: '14px',
                                    fontWeight: 600,
                                    marginBottom: '12px',
                                    display: 'flex',
                                    alignItems: 'center',
                                    gap: '8px',
                                }}
                            >
                                <span>🎵</span>
                                音频配置
                            </div>
                            <div
                                style={{
                                    display: 'flex',
                                    flexDirection: 'column',
                                    gap: '12px',
                                }}
                            >
                                <div
                                    style={{
                                        color: 'rgba(255, 255, 255, 0.9)',
                                        fontSize: '13px',
                                        display: 'flex',
                                        alignItems: 'center',
                                        gap: '8px',
                                        padding: '6px 8px',
                                        backgroundColor: 'rgba(0, 0, 0, 0.2)',
                                        borderRadius: '4px',
                                    }}
                                >
                                    <span style={{ color: '#1890ff' }}>🔊</span>
                                    <span>音量: 100%</span>
                                    <span style={{ color: '#52c41a', fontSize: '11px' }}>(默认设置)</span>
                                </div>

                                {/* 自动转文字选项 */}
                                <div
                                    style={{
                                        display: 'flex',
                                        alignItems: 'center',
                                        justifyContent: 'space-between',
                                        padding: '8px 12px',
                                        backgroundColor: 'rgba(0, 0, 0, 0.3)',
                                        borderRadius: '6px',
                                        border: '1px solid rgba(82, 196, 26, 0.3)',
                                    }}
                                >
                                    <div style={{ display: 'flex', alignItems: 'center', gap: '8px' }}>
                                        <span style={{ color: '#faad14' }}>📝</span>
                                        <span style={{ color: 'rgba(255, 255, 255, 0.9)', fontSize: '13px' }}>自动导入音频旁白</span>
                                    </div>
                                    <Switch
                                        checked={enableTranscription}
                                        onChange={setEnableTranscription}
                                        size="small"
                                        style={{
                                            backgroundColor: enableTranscription ? '#52c41a' : '#434343',
                                        }}
                                    />
                                </div>

                                {enableTranscription && (
                                    <div
                                        style={{
                                            color: 'rgba(255, 255, 255, 0.7)',
                                            fontSize: '12px',
                                            padding: '6px 8px',
                                            backgroundColor: 'rgba(24, 144, 255, 0.1)',
                                            borderRadius: '4px',
                                            border: '1px solid rgba(24, 144, 255, 0.3)',
                                        }}
                                    >
                                        <span style={{ color: '#1890ff' }}>ℹ️</span>
                                        <span style={{ marginLeft: '6px' }}>将自动识别音频内容并生成文字片段，如果识别失败音频片段仍会正常添加</span>
                                    </div>
                                )}
                            </div>
                        </div>
                    )}

                    {/* 隐藏的音量配置字段 */}
                    <Form.Item name={['segment_config', 'volume']} style={{ display: 'none' }}>
                        <InputNumber />
                    </Form.Item>
                </Form>

                {/* 自定义底部按钮区域 */}
                <div
                    style={{
                        marginTop: '32px',
                        paddingTop: '20px',
                        borderTop: '1px solid #434343',
                        display: 'flex',
                        justifyContent: 'space-between',
                        alignItems: 'center',
                        background: 'linear-gradient(90deg, transparent 0%, rgba(255, 255, 255, 0.05) 50%, transparent 100%)',
                    }}
                >
                    <Button
                        onClick={handleCancel}
                        disabled={uploading}
                        size="large"
                        style={{
                            minWidth: '100px',
                            height: '40px',
                            borderRadius: '6px',
                            fontWeight: 500,
                        }}
                    >
                        取消
                    </Button>

                    {audioFile ? (
                        <Button
                            type="primary"
                            icon={<UploadOutlined />}
                            onClick={handleUploadAndSubmit}
                            loading={uploading}
                            disabled={uploading}
                            size="large"
                            style={{
                                minWidth: '120px',
                                height: '40px',
                                borderRadius: '6px',
                                fontWeight: 600,
                                background: uploading ? 'linear-gradient(135deg, #1890ff 0%, #40a9ff 100%)' : 'linear-gradient(135deg, #1890ff 0%, #40a9ff 100%)',
                                border: 'none',
                                boxShadow: '0 2px 8px rgba(24, 144, 255, 0.3)',
                            }}
                        >
                            {uploading ? '上传中...' : '确定添加'}
                        </Button>
                    ) : (
                        <Upload {...uploadProps}>
                            <Button
                                icon={<UploadOutlined />}
                                size="large"
                                style={{
                                    minWidth: '160px',
                                    height: '40px',
                                    borderRadius: '6px',
                                    fontWeight: 500,
                                    background: 'linear-gradient(135deg, #2a2a2a 0%, #3a3a3a 100%)',
                                    border: '1px solid #434343',
                                    color: '#ffffff',
                                    boxShadow: '0 2px 4px rgba(0, 0, 0, 0.2)',
                                }}
                            >
                                选择音频文件
                            </Button>
                        </Upload>
                    )}
                </div>
            </ConfigProvider>
        </Modal>
    );
};

export default AddAudioClipModal;
